#! /usr/bin/env python
# -*- coding: utf-8 -*-

'''
界面逻辑
'''
__author__ = "jakey.chen"
__version__ = "v1.0"

import time
import Tkinter as tk
import threading
import datetime
import telnetlib
import webbrowser
import logging

from UI import LoginUI
from UI import ChatRoomUI
from DAL import db
from models import User

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S')

class MainLoginUI(LoginUI.LoginUI):
    def __init__(self, master=None):
        super(MainLoginUI, self).__init__()
        db.create_engine('jakey', '168168', 'jakey', host="10.10.58.72")
        self.root = master

        # self.userStr.set("Jakey.Chen")
        # self.passwdStr.set("cjs168")

    def Login(self):
        '''
        登录
        '''
        self.username = self.userStr.get().strip()
        self.password = self.passwdStr.get().strip()

        if self.username == "admin" and self.password=="admin":
            self.root.destroy()
            self.enter_char_room()
            return

        if self.username == "user" and self.password=="user":
            self.root.destroy()
            self.enter_char_room()
            return

        user = User.find_first('where name=? and password=?', self.username, self.password)
        if not user:
            url = "http://10.10.58.72:8000/register"
            webbrowser.open_new_tab(url)
            self.userStr.set("register~")
            self.passwdStr.set("")
        else:
            self.root.destroy()
            self.enter_char_room()

    def enter_char_room(self):
        '''
        打开群聊框
        '''
        root = tk.Tk()
        root.title("Nonsense ChatRoom")

        # root.update()
        w = root.winfo_screenwidth()
        h = root.winfo_screenheight()
        # rootsize = tuple(int(_) for _ in root.geometry().split('+')[0].split('x'))
        rootsize = (810, 622)
        x = w/2 - rootsize[0]/2
        y = h/2 - rootsize[1]/2
        root.geometry("%dx%d+%d+%d" % (rootsize + (x, y)))

        MainChatRoomUI(master=root, user=self.username)
        root.resizable(False, False)
        root.mainloop()

class MainChatRoomUI(ChatRoomUI.ChatRoomUI):
    def __init__(self, master=None, **kv):
        super(MainChatRoomUI, self).__init__()
        self.root = master
        self.user = kv["user"]
        self.list_box_users = list()
        self.frm_status_label["text"] = "Current User: " + self.user

        self.con = telnetlib.Telnet()

        self.login()

        threading_recieve = threading.Thread(target=self.thread_recieve)
        threading_recieve.setDaemon(True)
        threading_recieve.start()

        self.find_all_users()

    def Close(self):
        '''
        关闭窗口
        '''
        self.con.write('logout\n')
        self.con.close()
        self.root.destroy()

    def Send(self):
        '''
        发送消息到服务器
        '''
        message = self.frm_left_send_text.get("0.0", "end").strip().encode("utf-8")
        if message != '':
            self.con.write('say ' + message + '\n')
            self.frm_left_send_text.delete("0.0", "end")

    def login(self):
        '''
        登陆处理
        '''
        logging.debug("login")
        try:
            self.con.open("10.10.58.72", port=6666, timeout=10)
        except:
            self.con.open("127.0.0.1", port=6666, timeout=10)
        response = self.con.read_some()
        
        if response != 'Connect Success':
            logging.info("Connect Fail")
            logging.info()
            return
        self.con.write('login ' + self.user + '\n')

        response = self.con.read_some()
        
        if response == 'UserName Empty':
            logging.info("UserName Empty")
        elif response == 'UserName Exist':
            logging.info("UserName Exist")
        else:
            logging.info("Login sccuess")

    def find_all_users(self):
        '''
        查询当前在线用户
        '''
        self.con.write('look\n')

    def thread_recieve(self):
        '''
        线程接收服务器的消息
        '''
        while True:
            time.sleep(0.25)
            result = self.con.read_very_eager()
            if result != '':
                result_list = result.split(":")
                if len(result_list) > 1:
                    len_user = len(result_list[0]) + 2
                    result = result[len_user:].strip()
                    temp = result_list[0]
                else:
                    temp = "System"
                    if "entered" in result:
                        self.frm_right_listbox.insert("end", result.split(" ")[0])
                    elif "left" in result:
                        index = list(self.frm_right_listbox.get(0, self.frm_right_listbox.size())).index(result.split(" ")[0])
                        self.frm_right_listbox.delete(index)
                    else:
                        self.frm_left_revieve_text.insert("end", result + "\n")

                if temp == "Online Users":
                    for user in result.split("\n"):
                        self.frm_right_listbox.insert("end", user)
                else:
                    if temp == self.user:
                        bg_date = "lightgreen"
                    elif temp == "System":
                        bg_date = "pink"
                        result = result.strip()
                    else:
                        bg_date = "lightblue"
                    self.frm_left_revieve_text.insert("end", temp + " [" + str(datetime.datetime.now())
                                                      + "]:\n", bg_date)
                    self.frm_left_revieve_text.insert("end", result + "\n")
                    self.frm_left_revieve_text.see("end")
           

if __name__ == '__main__':
    '''
    main loop
    '''
    root = tk.Tk()
    root.title("Login")

    w = root.winfo_screenwidth()
    h = root.winfo_screenheight()
    rootsize = (396, 214)
    x = w/2 - rootsize[0]/2
    y = h/2 - rootsize[1]/2
    root.geometry("%dx%d+%d+%d" % (rootsize + (x, y)))

    MainLoginUI(master=root)
    root.resizable(False, False)
    root.mainloop()